<?php

namespace App\Http\Controllers\Setting;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use DB, Breadcrumbs, Toastr;
use App\Repositories\PermissionRepositoryEloquent;
use App\Repositories\RoleRepositoryEloquent;
use App\Http\Requests\RoleCreateRequest;
use App\Http\Requests\RoleUpdateRequest;

class RoleController extends Controller
{
    protected $role;
    protected $permission;

    public function __construct(RoleRepositoryEloquent $role, PermissionRepositoryEloquent $permission)
    {
        $this->role = $role;
        $this->permission = $permission;
    }

    public function index(Request $request)
    {
        $data['title'] = '角色管理';
        $data['role'] = DB::table('roles')->orderBy('id', 'desc')->get();
        $where = [];
        if($request->input('id')) $where['id'] =  $request->input('id');
        $data['roles'] = DB::table('roles')->select('*')->where($where)->orderBy('id', 'desc')->paginate(5);
        $data['roles']->appends($where)->render();
        return view('setting.role.index', $data);
    }

    public function store(RoleCreateRequest $request)
    {
        $res = $this->role->create($request->all());
        if($res) return response()->json(['ack' => 1, 'msg' => '添加成功']);
        return response()->json(['ack' => 0, 'msg' => '请求参数错误']);
    }

    public function update(RoleUpdateRequest $request, $id)
    {
        $res = $this->role->update($request->all(), $id);
        if($res) return response()->json(['ack' => 1, 'msg' => '添加成功']);
        return response()->json(['ack' => 0, 'msg' => '请求参数错误']);
    }

    public function destroy($id)
    {
        $result = $this->role->delete($id);
        return response()->json(['ack' => $result]);
    }

    public function destroyAll(Request $request)
    {
        if(!($ids = $request->get('ids', []))) {
            return response()->json(['ack' => 0, 'msg' => '请求参数错误']);
        }
        foreach ($ids as $id)  $this->role->delete($id);
        return response()->json(['ack' => 1]);
    }

    public function permission($id)
    {
        $data['title'] = '权限';
        $data['role'] = $this->role->find($id);
        $data['permissions'] = $this->permission->getTopPermission();
        $data['rolePermissions'] = $this->role->rolePermissions($id);
        return view('setting.role.permission', $data);
    }

    public function storePermission($id, Request $request)
    {
        $result = $this->role->savePermissions($id, $request->input('permissions', []));
        return response()->json($result ? ['ack' => 1] : ['ack' => 0]);
    }
}